﻿using System;
using System.Collections.Generic;
using System.Runtime.ConstrainedExecution;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

using Utils.Weixin.Pay.Result;

namespace Utils.Weixin.Pay.Helper
{
    public class Encrypter : IDisposable
    {
        private readonly X509Certificate2 x509Certificate;

        private readonly RSA rsa;

        public readonly string SerialNo;

        public Encrypter(CertificateResult cert)
        {
            SerialNo = cert.SerialNo;
            x509Certificate = new X509Certificate2(Encoding.UTF8.GetBytes(cert.CertificateText));
            rsa = (RSA)x509Certificate.PublicKey.Key;
        }

        public string Encrypt(string message)
        {
            if (message == null)
            {
                return null;
            }
            var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(message), RSAEncryptionPadding.OaepSHA1);
            return Convert.ToBase64String(buff);
        }

        public void Dispose()
        {
            x509Certificate.Dispose();
            rsa.Dispose();
        }
    }
}
